'use strict'

function Depts(){
	this.values = {};
	this.groupedDept = {};
	this.groupedDepts = {};
}

Depts.prototype.add = function(row,reader){
	var entity = reader(row),
		existed;

	if( entity!==undefined && entity.key!=undefined ){
		existed = this.values[entity.key];

		if( existed === undefined ){
			entity.records = {};
			existed = this.values[entity.key] = entity;
		}
		existed.records[entity.patientId] = true;
	}
}

Depts.prototype.groupDept = function(){
	var key,
		newKey,
		recordKey,
		entity,
		depts,
		time,
		idx=0,
		count =0 ,
		existed;

	for(key in this.values){
		entity = this.values[key];
	   	depts = key.split('__')[0].split(',');
		time = key.split('__')[1];	

		for(idx=0;idx<depts.length;idx++){
			newKey = depts[idx]+'__'+time;
			existed = this.groupedDept[newKey];

			if( existed === undefined ){
				this.groupedDept[newKey] = [];
			}
			this.groupedDept[newKey] = this.groupedDept[newKey].concat(Object.keys(entity.records));
		}
	}
}


Depts.prototype.groupDepts = function(){
	var key,recordKey,
		entity,
		existed;

	for(key in this.values){
		entity = this.values[key];
		existed = this.groupedDepts[key];

		if( existed === undefined ){
			this.groupedDepts[key] = [];
		}
		this.groupedDepts[key] = this.groupedDepts[key].concat(Object.keys(entity.records));
	}
}

Depts.prototype.show = function(){
	var key;
	console.log('==================================');
	console.log('====dept: '+ Object.keys(this.values).length);
	for( key in this.values ){
		console.log( key + ' > '+ this.values[key].time + ' '+ Object.keys(this.values[key].records) );
	}
}

Depts.prototype.showGroupedDept = function(){
	var key;
	console.log('==================================');
	console.log('====dept-groupedDept: '+ Object.keys(this.groupedDept).length);
	for( key in this.groupedDept ){
		console.log( key + ' > '+ this.groupedDept[key]);
	}

}

Depts.prototype.showGroupedDepts = function(){
	var key;
	console.log('==================================');
	console.log('====dept-groupedDepts: '+Object.keys(this.groupedDepts).length);
	for( key in this.groupedDepts ){
		console.log( key + ' > '+ this.groupedDepts[key]);
	}
}

module.exports = Depts;
